//
//  ObserverCameraController.m
//  Rail
//
//  Created by hychen on 2018/3/2.
//  Copyright © 2018年 Hychen. All rights reserved.
//

#import "ObserverCameraController.h"
#import "YCTextView.h"
#import "UIImageView+ObserverCamera.h"
#import "SelectFactoryViewController.h"
#import "UIImage+DP.h"

@interface ObserverCameraController ()<YCTextViewDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate,UIScrollViewDelegate>

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *scrollViewWidthConstraints;

@property (weak, nonatomic) IBOutlet UIScrollView *scrollView;

@property (weak, nonatomic) IBOutlet UIView *selectFactoryView;
@property (weak, nonatomic) IBOutlet UILabel *workLabel;
@property (weak, nonatomic) IBOutlet UILabel *photoCountLabel;
@property (weak, nonatomic) IBOutlet UIImageView *leftImage;
@property (weak, nonatomic) IBOutlet UIImageView *midImage;
@property (weak, nonatomic) IBOutlet UIImageView *rightImage;
@property (weak, nonatomic) IBOutlet UIView *textViewContainer;

@property (nonatomic, strong) YCTextView *textView;

@property (nonatomic, assign) NSInteger tapIndex;

@property (nonatomic, strong) NSMutableArray *imageArray;

@property (nonatomic, strong) UIImage *uploadLeftImage;
@property (nonatomic, strong) UIImage *uploadMidImage;
@property (nonatomic, strong) UIImage *uploadRightImage;

@property (nonatomic, copy) NSString *areaId;

@property (nonatomic, assign) BOOL isSelectWorkArea;

@property (nonatomic, assign) BOOL isUploading;
@end

@implementation ObserverCameraController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self.navigationItem addSimpleTitleView:@"巡线拍照"];
    
    self.scrollView.delegate = self;
    
    self.textView = [[YCTextView alloc] init];
    self.textView.font = [UIFont systemFontOfSize:14.f];
    self.textView.textColor = Color_RGB(56, 56, 56);
    self.textView.delegate = self;
    self.textView.limitTextLength = 120;
    self.textView.limitStyle = LimitStyleExistAndAll;
    self.textView.placeholder = @"请输入备注信息";
    [self.textView setLimitTextLengthBlock:^{
        
    }];
    
    [self.textViewContainer addSubview:self.textView];
    
    self.textView.layer.cornerRadius = 5.f;
    self.textView.layer.masksToBounds = YES;
    self.textView.layer.borderColor = [UIColor lightGrayColor].CGColor;
    self.textView.layer.borderWidth = 0.5f;
    
    [self.textView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.textViewContainer);
    }];
    
    BMWeakSelf
    [self.selectFactoryView addTapGestureWithBlock:^(UIGestureRecognizer *gestureRecoginzer) {
        SelectFactoryViewController *vc = [SelectFactoryViewController new];
        vc.style = SelectFactoryControllerStyleScanSelectFactory;
        //回调
        [vc setBlockCallBack:^(NSString *areaId, NSString *areaName) {
            weakSelf.workLabel.text = areaName?:@"";
            weakSelf.isSelectWorkArea = YES;
            weakSelf.areaId = areaId;
        }];
        [weakSelf.navigationController pushViewController:vc animated:YES];
    }];
    [self addGesture:self.leftImage];
    [self addGesture:self.midImage];
    [self addGesture:self.rightImage];
    
    [self countPhotoNum];
    
    self.workLabel.textColor = Color_RGB(86, 86, 86);
    self.workLabel.text = @"请选择工区";
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.scrollViewWidthConstraints.constant = SCREEN_WIDTH;
}

- (void)addGesture:(UIView *)view {
    [view addTapGestureWithTarget:self action:@selector(imageTap:)];
    [view addLongPressGestureWithTarget:self action:@selector(imageLongPress:) minDuration:0.8];
}

- (void)imageTap:(UIGestureRecognizer *)gesture {
    UIImageView *imageView = (UIImageView *)gesture.view;
    self.tapIndex = imageView.tag;
    [self addImageAlertSheet];
}

- (void)imageLongPress:(UIGestureRecognizer *)gesture {
    if (gesture.state != UIGestureRecognizerStateBegan) {
        return;
    }
    UIImageView *imageView = (UIImageView *)gesture.view;
    
    if (imageView.hasImage) {
        
        if (imageView.tag == 1000 && self.imageArray.count > 0) {
            [self.imageArray removeObjectAtIndex:0];
        }
        else if (imageView.tag == 1001 && self.imageArray.count > 1) {
            [self.imageArray removeObjectAtIndex:1];
        }
        else if (imageView.tag == 1002 && self.imageArray.count > 2) {
            [self.imageArray removeObjectAtIndex:2];
        }
        
        self.leftImage.image = [self cameraDefaultImage];
        self.leftImage.hasImage = NO;
        self.midImage.image = [self cameraDefaultImage];
        self.midImage.hasImage = NO;
        self.rightImage.image = [self cameraDefaultImage];
        self.rightImage.hasImage = NO;
        
        if ([self.imageArray objectAtIndexSafe:0]) {
            self.leftImage.image = [self.imageArray objectAtIndexSafe:0];
            self.leftImage.hasImage = YES;
        }
        if ([self.imageArray objectAtIndexSafe:1]) {
            self.midImage.image = [self.imageArray objectAtIndexSafe:1];
            self.midImage.hasImage = YES;
        }
        if ([self.imageArray objectAtIndexSafe:2]) {
            self.rightImage.image = [self.imageArray objectAtIndexSafe:2];
            self.rightImage.hasImage = YES;
        }
    }
    
    [self countPhotoNum];
}

- (UIImage *)cameraDefaultImage {
    return [UIImage imageNamed:@"app_add_picture_img"];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)_submitButton {
    BMWeakSelf
    UIImage *image1 = [self.imageArray objectAtIndexSafe:0];
    UIImage *image2 = [self.imageArray objectAtIndexSafe:1];
    UIImage *image3 = [self.imageArray objectAtIndexSafe:2];
    self.isUploading = YES;
    Show_Msg(@"上传中")
    
    [HttpRequest uploadPatrolLineDataWithAreaId:self.areaId deviceId:@"" deviceName:@"" channelName:@"" note:self.textView.text?:@"" image1:image1 image2:image2 image3:image3 success:^(id object) {
        
        weakSelf.isUploading = NO;
        
        if (weakSelf.BlockCameraSuccess) {
            weakSelf.BlockCameraSuccess();
        }
        
        //成功则返回上一级页面
        Show_Msg_Success(@"上传成功")
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [weakSelf.navigationController popViewControllerAnimated:YES];
        });
        
    } failure:^(NSString *code, NSString *msg) {
        weakSelf.isUploading = NO;
        Show_Msg_Error(msg?:@"上传失败")
    }];
    
}

- (IBAction)submitButton:(UIButton *)sender {
    
    BMWeakSelf
    if (self.isUploading) {
        return;
    }
    
    if (![self.areaId objectIsNotEmpty]) {
        Show_Msg_Error(@"请选择工区")
        return;
    }
    if (self.imageArray.count < 1) {
        Show_Msg_Error(@"请至少选择一张图片")
        return;
    }
    
    if (![BMUtils checkOpen4gAutoUploadWithCompletion:^{
        [weakSelf _submitButton];
    }]) {
        return;
    }
    
    [self _submitButton];

}

- (void)YCTextView:(YCTextView *)YCTextView textDidChanged:(NSString *)text {
    
}

- (void)countPhotoNum {
    NSInteger count = 0;
    if (self.leftImage.hasImage) {
        count++;
    }
    
    if (self.midImage.hasImage) {
        count++;
    }
    
    if (self.rightImage.hasImage) {
        count++;
    }
    
    self.photoCountLabel.text = [NSString stringWithFormat:@"%ld/3",(long)count];
}

#pragma mark - image
- (void)addImageAlertSheet {
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    
    UIAlertAction *action = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self alertClickedButtonAtIndex:0];
    }];
    UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"从手机相册选择" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self alertClickedButtonAtIndex:1];
    }];
    UIAlertAction *action3 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    
    [alert addAction:action];
    [alert addAction:action1];
    [alert addAction:action3];
    
    
    [self.navigationController presentViewController:alert animated:YES completion:nil];
}

- (void)alertClickedButtonAtIndex:(NSInteger)buttonIndex{
    switch (buttonIndex) {
        case 0:
            //来源:相机
            if ([self requestCameraAuth]) {
                [self goToCameraVc];
            }
            return;
        case 1:
            //来源:相册
            [self checkPhotoAuth];
            return;
        case 2:
            return;
    }
}

- (void)goToCameraVc {
    // 跳转到相机或相册页面
    UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
    imagePickerController.delegate = self;
    imagePickerController.allowsEditing = YES;
    imagePickerController.sourceType = UIImagePickerControllerSourceTypeCamera;
    
    [self.navigationController presentViewController:imagePickerController animated:YES completion:^{
        
    }];
}

- (void)goToPhotoVc {
    // 跳转到相机或相册页面
    UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
    imagePickerController.delegate = self;
    imagePickerController.allowsEditing = YES;
    imagePickerController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    
    [self.navigationController presentViewController:imagePickerController animated:YES completion:^{
        
    }];
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    [picker dismissViewControllerAnimated:YES completion:^{
        
    }];
    
    UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
    if (![image isKindOfClass:[UIImage class]]) {
        Show_Msg_Error(@"获取失败")
        return;
    }
    image = [image zipImage];
    
    if (self.tapIndex == 1000) {
//        self.midImage.hidden = NO;
        self.leftImage.image = image;
        self.leftImage.hasImage = YES;
    }
    else if (self.tapIndex == 1001) {
//        self.rightImage.hidden = NO;
        self.midImage.image = image;
        self.midImage.hasImage = YES;
    }
    else if (self.tapIndex == 1002) {
        
        self.rightImage.image = image;
        self.rightImage.hasImage = YES;
    }
    image = [image zipImage];
    [self.imageArray addObject:image];
    [self countPhotoNum];
}

- (UIImage *)imageWithImage:(UIImage*)image
               scaledToSize:(CGSize)newSize {
    UIGraphicsBeginImageContext(newSize);
    [image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
    UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return newImage;
}

- (void)setIsSelectWorkArea:(BOOL)isSelectWorkArea {
    _isSelectWorkArea = isSelectWorkArea;
    self.workLabel.textColor = isSelectWorkArea?kBlackColor:Color_RGB(86, 86, 86);
}

- (NSMutableArray *)imageArray {
    if (!_imageArray) {
        _imageArray = [NSMutableArray array];
    }
    return _imageArray;
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    [self.view endEditing:YES];
}

- (BOOL)requestCameraAuth {
    AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
    if (authStatus ==AVAuthorizationStatusRestricted ||//此应用程序没有被授权访问的照片数据。可能是家长控制权限
        authStatus ==AVAuthorizationStatusDenied)  //用户已经明确否认了这一照片数据的应用程序访问
    {
        [UIAlertView bk_showAlertViewWithTitle:@"提示" message:@"需要开启相机权限才能拍摄照片哦" cancelButtonTitle:@"取消" otherButtonTitles:@[@"去开启"] handler:^(UIAlertView *alertView, NSInteger buttonIndex) {
            if (buttonIndex == 1) {
                if (IOS8) {
                    NSURL *settingURL = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
                    if ([[UIApplication sharedApplication] canOpenURL:settingURL]) {
                        [[UIApplication sharedApplication] openURL:settingURL];
                    }
                }
            }
        }];
        return NO;
    }
    return YES;
}

// 检查授权
- (void)checkPhotoAuth
{
    BMWeakSelf
    [BMPhotoIOAuthTool checkAuthForPhotoWithAuthedStatus:^(PHAuthorizationStatus status) {
        [weakSelf goToPhotoVc];
    } denied:^(PHAuthorizationStatus status) {
        [weakSelf requestPhotoAuth];
    } noRequest:^(PHAuthorizationStatus status) {
        [weakSelf requestPhotoAuth];
    }];
}

// 请求授权
- (void)requestPhotoAuth
{
    BMWeakSelf
    [BMPhotoIOAuthTool requestAuthForPhotoWithAuthedStatus:^(PHAuthorizationStatus status) {
        [weakSelf goToPhotoVc];
    } denied:^(PHAuthorizationStatus status) {
        [UIAlertView bk_showAlertViewWithTitle:@"提示" message:@"需要开启相册权限才能查看照片哦" cancelButtonTitle:@"取消" otherButtonTitles:@[@"去开启"] handler:^(UIAlertView *alertView, NSInteger buttonIndex) {
            if (buttonIndex == 1) {
                if (IOS8) {
                    NSURL *settingURL = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
                    if ([[UIApplication sharedApplication] canOpenURL:settingURL]) {
                        [[UIApplication sharedApplication] openURL:settingURL];
                    }
                }
            }
        }];
    }];
}
@end
